package com.example.baseapp.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * WebLogAspect class
 * 使用切面实现
 * @author zhangl
 * @date 2022/3/24 20:58
 */
@Slf4j
//@Aspect
public class WebLogAspect {
    /**
     * 以 controller 包下定义的所有请求为切入点
     */
    @Pointcut("execution(public * com.example.baseapp.*.controller.*.*(..))")
    public void webLog(){}
    /**
     * 在切点之前织入
     * @param joinPoint
     *
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint){
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        log.info("\nMethod---->: [{}] \nIP-------->: [{}] \nURL------->: [{}] \nRequest---->: [{}]",
                request.getMethod(),
                request.getRemoteAddr(),
                request.getRequestURL().toString(),
                joinPoint.getArgs());

    }
    /**
     * 在切点之后织入
     *
     */
    @After("webLog()")
    public void doAfter() {

    }
    /**
     * 环绕
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        // 打印出参
        log.info("Response -->: {}", JSON.toJSON(result));
        // 执行耗时
        log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
        return result;
    }
}
